// pages/fb_chatRoom/fb_chatRoom.js
import tool from '../../modules/tool'
import ws from '../../modules/ws';
let gettingBeforeData = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    wsDisabled: false,
    reconnecting: false,
    input: '',
    anchor: '',
    scrollTop: 0, // 当前滚动位置
    isBottom: false, // 是否滚动到底部
    isTop: true, // 是否滚动到顶部
    showMoreBoard: false,
  },

  // 显示更多面板
  handleShowMoreBoard() {
    console.log(this.data)
    this.setData({
      showMoreBoard: true
    })
  },

  // 隐藏更多面板
  handleHideMoreBoard() {
    this.setData({
      showMoreBoard: false
    })
  },

  // 获取滚动位置
  getScrollPosition(event) {
    this.setData({
      scrollTop: event.detail.scrollTop
    });
  },

  // 判断是否滚动到底部
  async checkIfBottom(event) {
    const scrollHeight = event.detail.scrollHeight;
    const scrollTop = event.detail.scrollTop;
    const clientHeight = await new Promise((resolve, reject) => {
      wx.createSelectorQuery()
        .select('#scrollView')
        .boundingClientRect(rect => {
          resolve(rect.height)
        })
        .exec();
    });

    const isBottom = scrollTop + clientHeight >= scrollHeight - 50;
    this.setData({
      isBottom
    });
  },

  // 判断是否滚动到顶部
  checkIfTop(event) {
    const isTop = event.detail.scrollTop <= 5;
    this.setData({
      isTop
    });
  },

  // 监听滚动事件
  onScroll(event) {
    this.getScrollPosition(event);
    this.checkIfBottom(event);
    this.checkIfTop(event);
  },

  handleInput(e) {
    this.setData({
      input: e.detail.value
    })
  },

  toBottom() {
    this.setData({
      anchor: 'bottomAnchor'
    })
  },

  toLocationBeforeGetData() {
    this.setData({
      anchor: 'getDataScrollTo'
    })
  },

  handleMessageClick(e) {
    e = e.currentTarget.dataset.item
    if (e.content_isURL) {
      tool.handleShowWebView(e.content)
    }
    if (e.content_isObject && e.content?.type === 'image') {
      this.handlePreviewImage(e.content.data)
    }
  },

  handlePreviewImage(currentFileName) {
    let arr = []
    for (let i = 0; i < this.data.data.list.length; i++) {
      let currentItem = this.data.data.list[i]
      if (currentItem.content_isObject && currentItem.content?.type === 'image') {
        arr.push(this.data.imagePrefix + currentItem.content.data)
      }
    }
    wx.previewImage({
      urls: arr,
      current: this.data.imagePrefix + currentFileName
    })
  },

  async handleSendImage() {
    let re = await tool.chooseImages(1)
    this.setData({
      showMoreBoard: false
    })
    if (re && re.length) {
      re = re[0]
      re = await tool.compressImage(re)
      re = await tool.uploadFileToServer(re)
      try {
        re = JSON.parse(re)
      } catch (error) {

      }
      if (re.status) {
        re = re.data
        this.handleSend(JSON.stringify({
          type: 'image',
          data: re
        }))
      } else {
        tool.handleShowToast(`${re.content}`, 'error')
      }
    }
  },

  handleSend(input) {
    if (typeof input === 'object' && this.data.input === '') return
    if (typeof input === 'object') {
      input = this.data.input
    }
    tool.flow(async () => {
      let re = await tool.requestData('/chatRoom/sendMessage', {
        openId: tool.store.getItem('openId'),
        chatRoomId: this.data.chatRoomId,
        isHandleUser: this.data.isHandleUser,
        content: input
      })
      if (re.status) {
        this.setData({
          input: ''
        })
      } else {
        throw re.content
      }
    }, err => tool.handleShowToast(`${err}`, 'error', 800))
  },

  handleBack() {
    wx.navigateBack()
  },

  async handleShowCurrentUserFeedBacks() {
    if (!this.data.isHandleUser) return
    tool.handleShowFBMyPage(this.data.data.chatRoomInfo.userOpenId, this.data.data.chatRoomInfo.userOpenId_read, () => {
      this.handleHideMoreBoard()
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    tool.setPageData(this)
    this.setData({
      openId: tool.store.getItem('openId')
    })
    let data = tool.store.getItem('chatRoomData')
    tool.store.removeItem('chatRoomData')
    if (data) {
      this.setData(data)
    } else {
      wx.navigateBack()
      return
    }
    this.handleSetZero()
    tool.store.onChange('wsConnected', e => {
      if (e === -1) {
        this.setData({
          wsDisabled: true
        })
      } else {
        this.setData({
          wsDisabled: false,
          reconnecting: e === undefined ? true : false,
        })
      }
    })
    tool.store.onChange('chatMessage', e => {
      if (e.chatRoomId !== this.data.chatRoomId) return
      let isBottom = this.data.isBottom
      this.setData({
        data: (() => {
          try {
            let t = this.data.data
            t.list = tool.appendChatRoomMessageItem(t.list, e)
            return t
          } catch (error) {
            console.log(error)
          }

        })()
      })
      if (isBottom) {
        this.toBottom()
      }
      this.handleSetZero()
    })
    setTimeout(() => {
      this.toBottom()
    }, 50);
  },

  async handleGetBefore() {
    if (gettingBeforeData) return
    gettingBeforeData = true
    let finalId = this.data.data.list[0].id
    tool.flow(async () => {
      let re = await tool.requestData('/chatRoom/getChatHistoryList', {
        openId: tool.store.getItem('openId'),
        chatRoomId: this.data.chatRoomId,
        isHandleUser: this.data.isHandleUser,
        finalId
      }, 'post', false)
      gettingBeforeData = false
      if (re.status) {
        if (re.data.list && re.data.list.length) {
          let arr = this.data.data.list
          arr = arr.filter(item => item.type !== -2)
          arr = [...re.data.list, {
            type: -2
          }, ...arr]
          re.data.list = arr
          this.setData({
            data: re.data
          })

          await tool.wait(0.01)
          this.toLocationBeforeGetData()
        }

      } else {
        throw re.content
      }
    }, err => tool.handleShowToast(`${err}`, 'error', 800))
  },

  handleSetZero() {
    ws.send('setZero', {
      chatRoomId: this.data.chatRoomId,
      isHandleUser: this.data.isHandleUser
    })
    tool.store.setItem('setZero', {
      chatRoomId: this.data.chatRoomId,
      isHandleUser: this.data.isHandleUser
    })
  },

  handleEditNoteForHandleUser() {
    this.handleHideMoreBoard()
    let name = this.data.data.chatRoomInfo.userOpenId_read
    let noted = this.data.data.chatRoomInfo.handleUserNoted
    if (!noted) name = ''
    tool.controlInput('备注名称', '仅你自己可见，将会替换掉默认的OpenId后六位。', 'singleText', name, (e) => {
      tool.flow(async () => {
        let re = await tool.requestData('/chatRoom/setHandleUserNote', {
          chatRoomId: this.data.chatRoomId,
          handleUserNote: e
        })
        if (re.status) {
          wx.navigateBack()
          await tool.wait(0.4)
          tool.handleShowToast('成功')
          this.setData({
            data: (() => {
              let data = this.data.data
              data.chatRoomInfo.handleUserNoted = !!e
              if (!e) e = data.chatRoomInfo.userOpenId.slice(-6)
              data.chatRoomInfo.userOpenId_read = e
              tool.store.setItem('chatMessage', {})
              return data
            })()
          })
        } else {
          throw re.content
        }
      }, err => tool.handleShowToast(err, 'error'))
    }, (e) => {
      if (noted && e === name) {
        throw '未改动'
      }
      if (e.length > 10) throw '不能长于10个字'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})